﻿using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using ExcellentCRM.Site.Properties;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace ExcellentCRM.Site.Exts
{
    public class JsonNetResult : JsonResult
    {
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
                String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException(Resources.JsonRequest_GetNotAllowed);
            }

            HttpResponseBase response = context.HttpContext.Response;

            response.ContentType = !String.IsNullOrEmpty(ContentType)
                                       ? ContentType
                                       : "application/json";
            if (ContentEncoding != null)
            {
                response.ContentEncoding = ContentEncoding;
            }
            if (Data == null) return;
            var serializedObject =
                JsonConvert.SerializeObject(Data, Formatting.Indented,
                                            new JsonSerializerSettings
                                                {
                                                    ContractResolver =
                                                        new CamelCasePropertyNamesContractResolver(),
                                                    NullValueHandling =
                                                        NullValueHandling.Ignore
                                                });
            response.Write(serializedObject);
        }
    }
}